package com.utils.toast

import android.app.Application
import android.os.Build
import android.view.Gravity
import android.widget.Toast
import androidx.annotation.IntegerRes
import com.utils.ActivityUtils
import com.utils.toast.ext.IconToastView
import com.utils.toast.ext.TextToastView
import java.util.Objects

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 4/7/21
 */
object ToastUtils {

    private var application: Application? = null

    fun initToast(application: Application) {
        this.application = application
    }

    fun toastText(text: String?) {
        Objects.requireNonNull(application)
        createToast()?.apply {
            setGravity(Gravity.CENTER, 0, 0)
            setDuration(Toast.LENGTH_SHORT)

            val toastView = TextToastView(application!!).apply {
                this.text = text ?: ""
            }
            setView(toastView)
        }?.show()
    }

    fun toastIcon(@IntegerRes iconRes: Int, text: String?) {
        Objects.requireNonNull(application)
        createToast()?.apply {
            setGravity(Gravity.CENTER, 0, 0)
            setDuration(Toast.LENGTH_SHORT)
            val toastView = IconToastView(application!!).apply {
                img = iconRes
                this.text = text ?: ""
            }
            setView(toastView)
        }?.show()
    }

    private fun createToast(): IToast? {
        if (application == null) {
            throw NullPointerException("have not init ToastUtils.You have to invoke ToastUtils.init(Application) before.")
            return null
        }
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val foregroundActivity = ActivityUtils.getCurrentTopActivity()
            if (foregroundActivity != null && !foregroundActivity.isFinishing) {
                WindowToast(application!!)
            } else {
                SystemToast()
            }
        } else {
            SystemToast()
        }
    }
}